<template>
  <div class="game-page">
    <transition name="el-zoom-in-top">
      <el-form v-show="searchFormVisible" inline size="mini" :model="searchForm" ref="searchForm"
               @keyup.enter.native="searchHandle">
        <el-form-item prop="word" label="游戏检索">
          <el-input v-model="searchForm.word" clearable placeholder="请输入游戏名称"></el-input>
        </el-form-item>
        <el-form-item prop="startTime">
          <el-date-picker
            v-model="searchForm.startTime"
            type="datetime"
            placeholder="请选择开始时间"
            default-time="00:00:00"
            value-format="timestamp">
          </el-date-picker>
        </el-form-item>
        <el-form-item prop="endTime">
          <el-date-picker
            v-model="searchForm.endTime"
            type="datetime"
            placeholder="请选择结束时间"
            default-time="23:59:59"
            value-format="timestamp">
          </el-date-picker>
        </el-form-item>
        <el-form-item prop="status">
          <el-select v-model="searchForm.status" clearable placeholder="请选择状态">
            <el-option v-for="statusEnum in statusEnumList" :key="'status' + statusEnum.value"
                       :label="statusEnum.name" :value="statusEnum.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button :disabled="dataLoad" @click="searchHandle" type="primary" icon="el-icon-search">查询</el-button>
          <el-button :disabled="dataLoad" @click="resetFormHandle" plain icon="el-icon-refresh-right">重置</el-button>
        </el-form-item>
      </el-form>
    </transition>
    <div class="g-tool">
      <el-button :disabled="dataLoad" @click="$refs.gameDialog.initDialog(undefined)"
                 type="primary" size="mini" plain icon="el-icon-plus">添加</el-button>
      <el-button :disabled="gameSelection.length !== 1 || dataLoad"
                 @click="$refs.gameFlowDialog.initDialog(gameSelection[0].id)"
                 type="primary" size="mini" plain icon="el-icon-view">流水</el-button>
      <el-button :disabled="dataLoad || buttonLoad" @click="exportGameHandle"
                 type="success" size="mini" plain icon="el-icon-download">导出</el-button>
      <el-button :disabled="gameSelection.length === 0 || dataLoad || buttonLoad"
                 @click="updateGameStatusHandle(undefined, 0)"
                 type="success" size="mini" plain icon="el-icon-circle-plus-outline">启用</el-button>
      <el-button :disabled="gameSelection.length === 0 || dataLoad || buttonLoad"
                 @click="updateGameStatusHandle(undefined, 1)"
                 type="warning" size="mini" plain icon="el-icon-circle-close">禁用</el-button>
      <el-button :disabled="gameSelection.length === 0 || dataLoad || buttonLoad" @click="deleteGameHandle"
                 type="danger" size="mini" plain icon="el-icon-delete">删除</el-button>

      <right-tool-bar :search-visible="searchFormVisible" :search-load="dataLoad"
                      @toggle-search="searchFormVisible = !searchFormVisible" @refresh-table="getGameList" />
    </div>
    <el-table
      v-loading="dataLoad"
      element-loading-text="游戏列表加载中..."
      element-loading-spinner="el-icon-loading"
      :data="gameList"
      @sort-change="sortChangeHandle"
      @selection-change="(val) => this.gameSelection = val"
      ref="gameTable"
    >
      <el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
      <el-table-column sortable="custom" :sort-orders="sortOrders" prop="gameName" header-align="center" align="center"
                       label="游戏名称">
      </el-table-column>
      <el-table-column sortable="custom" :sort-orders="sortOrders" prop="startTime" header-align="center" align="center"
                       label="开始时间">
      </el-table-column>
      <el-table-column sortable="custom" :sort-orders="sortOrders" prop="endTime" header-align="center" align="center"
                       label="结束时间">
      </el-table-column>
      <el-table-column prop="status" header-align="center" align="center" label="状态">
        <template v-slot="{row}">
          <el-tag :type="row.status === 0 ? 'primary' : 'danger'">
            {{ row.status | baseFormat(statusEnumList) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="remark" header-align="center" align="center" label="备注"></el-table-column>
      <el-table-column sortable="custom" :sort-orders="sortOrders" prop="createTime" header-align="center"
                       align="center" label="创建时间">
      </el-table-column>
      <el-table-column prop="createUser" header-align="center" align="center" label="创建用户"></el-table-column>
      <el-table-column
        fixed="right"
        header-align="left"
        width="180"
        label="操作">
        <template v-slot="{ row }">
          <div>
            <el-button type="text" icon="el-icon-edit" @click="$refs.gameDialog.initDialog(row)">
              修改
            </el-button>
            <el-button v-if="row.status === 1" type="text" icon="el-icon-check"
                       @click="updateGameStatusHandle(row, 0)">
              启用
            </el-button>
            <el-button v-if="row.status === 0" type="text" icon="el-icon-close"
                       @click="updateGameStatusHandle(row, 1)">
              禁用
            </el-button>
          </div>
          <div>
            <el-button type="text" icon="el-icon-sugar" @click="goGamePrizePageHandle(row)">
              游戏奖品
            </el-button>
            <el-button type="text" icon="el-icon-user" @click="goGameUserPageHandle(row)">
              游戏用户
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :disabled="dataLoad"
      :current-page="searchForm.page"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="searchForm.limit"
      :total="totalNum"
      layout="total, sizes, prev, pager, next, jumper"
      class="paging">
    </el-pagination>

    <!-- 游戏添加/修改弹出框 -->
    <game-dialog ref="gameDialog" @refresh-table="getGameList" />

    <!-- 游戏流水弹出框 -->
    <game-flow-dialog ref="gameFlowDialog" />

  </div>
</template>

<script>
  import RightToolBar from "@/components/common/right-toolbar";
  import GameDialog from '@/components/game/save-update';
  import GameFlowDialog from "@/components/game/flow/game.vue";
  export default {
    name: 'admin-game-index',
    layout: 'admin',
    components: {
      RightToolBar,
      GameDialog,
      GameFlowDialog,
    },
    data() {
      return {
        // 游戏列表
        gameList: [],
        // 选中的游戏数据
        gameSelection: [],
        // 游戏总数
        totalNum: 0,
        // 状态枚举列表
        statusEnumList: [
          {
            name: '开始',
            value: 0
          },
          {
            name: '关闭',
            value: 1
          }
        ],
        // 表格排序字段排序方式
        sortOrders: ['ascending', 'descending'],
        // 游戏管理检索表单显示状态[true-显示 false-隐藏]
        searchFormVisible: true,
        // 游戏管理检索表单对象
        searchForm: {
          // 游戏名称
          word: '',
          // 游戏开始时间
          startTime: '',
          // 游戏结束时间
          endTime: '',
          // 状态
          status: '',
          // 当前展示页码
          page: 1,
          // 当前页显示个数
          limit: 10,
          // 排序字段
          field: 'id',
          // 排序方式
          order: 'descending',
        },
        // 数据加载状态[false-不加载 true-加载]
        dataLoad: false,
        // 按钮禁用状态[true-禁用 false-可用]
        buttonLoad: false,
      }
    },
    filters: {
      /**
       * 枚举映射方法
       * @param {number} value 参数值
       * @param {Array}  list  枚举列表
       */
      baseFormat(value, list) {
        for (let obj of list) {
          if (obj.value === value) {
            return obj.name;
          }
        }
        return '未知';
      }
    },
    asyncData({ app, params } ) {
      let searchForm = {
        word: '',
        startTime: '',
        endTime: '',
        status: '',
        page: 1,
        limit: 10,
        field: 'id',
        order: 'descending'
      }
      if (params.searchForm) {
        searchForm = JSON.parse(params.searchForm);
      }
      return app.$axios.$post('/game/page/list', searchForm)
        .then(({ data }) => {
          return {
            gameList: data.data,
            totalNum: data.totalNum,
            searchForm: searchForm
          }
        })
        .catch(() => {});
    },
    methods: {
      /**
       * 搜索游戏事件
       */
      searchHandle() {
        this.searchForm.page = 1;

        this.getGameList();
      },
      /**
       * 获取游戏列表方法
       */
      getGameList() {
        // 开始加载
        this.dataLoad = true;
        this.$axios.$post('/game/page/list', this.searchForm)
          .then(({ data }) => {
            this.gameList = data.data;
            this.totalNum = data.totalNum;
          })
          .catch(() => {})
          .finally(() => {
            // 结束加载
            this.dataLoad = false;
          })
      },
      /**
       * 使用游戏事件
       * @param {Object} game      游戏对象
       * @param {number} newStatus 新状态
       */
      updateGameStatusHandle(game, newStatus) {
        let data = {
          idList: [],
          status: newStatus
        }
        let message;
        if (game) {
          // 单个
          data.idList.push(game.id);
          message = `您确定要‘${newStatus === 0 ? '启用' : '禁用'}’${game.gameName}游戏吗，是否继续？`
        } else {
          // 批量
          data.idList = this.gameSelection.filter(_game => _game.status !== newStatus).map(_game => _game.id);
          if (data.idList.length === 0) {
            this.notify('', '温馨提示', `您选中的数据无需进行’${newStatus === 0 ? '启用' : '禁用'}‘操作`);
            return
          }
          message = `您确定要批量‘${newStatus === 0 ? '启用' : '禁用'}’游戏吗，是否继续？`
        }
        this.$confirm(message, '操作提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
            // 按钮禁用
            this.buttonLoad = true;
            return this.$axios.$post('/game/update/status', data);
          })
          .then(() => {
            let successMessage;
            if (game) {
              successMessage = `‘${newStatus === 0 ? '启用' : '禁用'}’${game.gameName}游戏操作成功`;
              // 更新状态
              game.status = newStatus;
            } else {
              successMessage = `批量‘${newStatus === 0 ? '启用' : '禁用'}’游戏操作成功`;
              // 更新状态
              this.gameSelection.forEach(_game => _game.status = newStatus);
              // 清空表格选中数据
              this.$refs.gameTable.clearSelection();
            }
            this.notify('success', '操作成功', successMessage);
          })
          .catch(err => {
            if (err.code === 409) {
              this.getGameList();
            }
          })
          .finally(() => {
            // 按钮恢复可使用
            this.buttonLoad = false;
          });
      },
      /**
       * 删除游戏事件
       */
      deleteGameHandle() {
        let idList = this.gameSelection.filter(game => game.id);

        this.$confirm('您确定要删除选中的游戏吗，是否继续？', '操作提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'danger'
        }).then(() => {
            // 按钮禁用
            this.buttonLoad = true;
            return this.$axios.$delete('/game/delete', { data: idList });
          })
          .then(() => {
            this.notify('success', '操作成功', '游戏数据删除成功');
            // 刷新表格
            this.getGameList();
          })
          .catch(err => {
            if (err.code === 409) {
              this.getGameList();
            }
          })
          .finally(() => {
            // 按钮恢复可使用
            this.buttonLoad = false;
          });
      },
      /**
       * 表格选择字段排序事件
       * @param {string} prop  排序字段
       * @param {string} order 排序方式
       */
      sortChangeHandle( { prop, order } ) {
        this.searchForm.page = 1;
        this.searchForm.field = prop;
        this.searchForm.order = order;

        this.getGameList();
      },
      /**
       * 每页显示个数变化事件
       * @param {number} size 最新显示个数值
       */
      sizeChangeHandle(size) {
        let searchForm = this.searchForm;
        searchForm.page = 1;
        searchForm.limit = size;
        this.getGameList();
      },
      /**
       * '点击特定页码'、'上一页'、'下一页'操作事件
       * @param {number} index 最新页码
       */
      currentChangeHandle(index) {
        let searchForm = this.searchForm;
        if (searchForm.page === index) {
          return;
        }
        searchForm.page = index;
        this.getGameList();
      },
      /**
       * 重置检索表单事件
       */
      resetFormHandle() {
        // 重置表单
        this.$refs.searchForm.resetFields();

        this.searchForm.page = 1;
      },
      /**
       * 跳转到游戏奖品管理页面事件
       * @param {Object} game 游戏对象
       */
      goGamePrizePageHandle(game) {
        this.$router.push({ name: 'admin-game-prize-gameId', params: { gameId: game.id, prePageSearchForm: JSON.stringify(this.searchForm)}});
      },
      /**
       * 跳转到游戏用户管理页面事件
       * @param {Object} game 游戏对象
       */
      goGameUserPageHandle(game) {
        this.$router.push({ name: 'admin-game-user-gameId', params: { gameId: game.id, prePageSearchForm: JSON.stringify(this.searchForm)}});
      },
      /**
       * 导出游戏数据事件
       */
      exportGameHandle() {
        let body = {
          taskType: 100,
          fields: [],
          downloadMode: 1,
          fileType: 0,
          dataType: 0,
          params: JSON.stringify(this.searchForm)
        }
        this.buttonLoad = true;
        this.$axios.$post('/common/export-task/add', body)
          .then(({ data }) => {
            this.notify('success', '游戏导出', '开始执行游戏数据导出');
            // 执行导出
            window.location.href = process.env.BASE_URL + '/common/export-task/run?taskId=' + data;
          })
          .catch(() => {})
          .finally(() => {
            this.buttonLoad = false;
          });
      }
    },
  }
</script>

<style scoped>
  .game-page .g-tool {
    margin-bottom: 7px;
  }
  .game-page .paging {
    text-align: right;
    margin: 7px;
  }
</style>
